import React, { useEffect, useState } from "react";
import { Button,  Modal, Popconfirm, message, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import "./AdsTable.css";
import { _getAds, _changePng, _delete } from "./Api";


const AdsTable = () => {

  const [adslist, setAdslist] = useState([]); //存储广告列表
  const [isModalOpen, setIsModalOpen] = useState(false); //初始化提示框
  const [pngFile, setPngFile] = useState(); //存储广告图片
  const [id, setId] = useState(""); // 存储修改图片的id


  useEffect(() => {
    const adsReq = async () => {
      try {
        const res = await _getAds();
        // const list = await res[0]
        setAdslist(res);
        console.log(res);
      } catch (err) {
        console.log("error:", err);
      }
    };
    adsReq();
  }, []);

  //修改图片模态框
  const showModal = (e) => {
    setId(e.id);
    console.log(e.id);
    
    setIsModalOpen(true);
  };

  const props = {
    name: "file", // 指定name属性，便于在表单提交或文件上传时识别
    beforeUpload: (file) => {    
      setPngFile(file);
      return false;// 阻止自动上传，改为手动处理
    },
    onChange: (info) => {
      // if (info.file.status !== 'uploading') {
      //   console.log(info.file, info.fileList);
      // }
    },
  };

  //确认新图片
  const handleOk = async () => {
    // 确保有文件被选中
    if (!pngFile) {
      message.error("请选择一个图片文件");
      return;
    }
    const formData = new FormData();
    formData.append('file', pngFile);
    console.log(pngFile);  
    
    try {
      await _changePng(id,formData);
      //重新渲染列表数据
      const res = await _getAds();
      // console.log(res);
      
      setAdslist(res);
      setIsModalOpen(false); // 关闭模态框
      setPngFile(null)
    } catch (err) {
      message.error("上传失败：" + err.message);
    }
  };
  //取消修改图片
  const handleCancel = () => {
    setPngFile(null)
    setIsModalOpen(false);
  };


  //删除广告确认框
  const confirm = async (e) => {   
    await _delete(e.id);
    message.success("删除成功");
    const res = await _getAds();
    setAdslist(res);
    console.log(res);
    
  };
  const cancel = () => {
    message.error("取消删除");
  };


  return (
    <>
    <table>
      <tr>
        <th>广告公司</th>
        <th>广告名称</th>
        <th>所属分类</th>
        <th>广告图片</th>
        <th>操作</th>
      </tr>
      {adslist.map((item) => (
        <tr key={item.id}>
          <td>{item.adCompany}</td>
          <td>{item.adName}</td>
          <td>{item.adCategory}</td>
          <td>
            <img src={item.file} alt={item.adName} className="adsPage" />
          </td>
          <td>
            <Button onClick={() => showModal(item)}>修改图片</Button>
            <Popconfirm
              title="删除："
              description="确认删除此广告吗？"
              onConfirm={() => confirm(item)}
              onCancel={cancel}
              okText="确认"
              cancelText="取消"
            >
              <Button danger>删除广告</Button>
            </Popconfirm>
          </td>
        </tr>
      ))}
    </table>

    {/* 修改广告图片模态框 */}
    <Modal
        title="请选择新图片："
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>上传图片</Button>
        </Upload>
      </Modal>
    </>
  );
};

export default AdsTable;
